<template>
  <div v-loading="queueLoading" class="container" ref="containerRef" curPageName="goods_document_card">
    <div class="title">
      <div class="title-text">{{ baseRef?.title }}</div>
      <div class="title-link">
        <el-button v-for="key in Object.keys(collapseTitle)" link @click="() => scrollToKey(key as CollapseItem)">
          {{ collapseTitle[key] }}
        </el-button>
      </div>
    </div>
    <el-scrollbar ref="scrollRef">
      <MerakCollapse v-model="collapseActive">
        <MerakCollapseItem :name="CollapseItem.base" :title="collapseTitle[CollapseItem.base]">
          <template #handler>
            <template v-if="collapseEdit[CollapseItem.base]">
              <el-button @click="() => baseRef?.onCancel().then(() => (collapseEdit[CollapseItem.base] = false))">
                {{ $t("merak.cancel") }}
              </el-button>
              <el-button type="primary" @click="handleSaveBase">{{ $t("merak.save") }}</el-button>
            </template>
            <el-button
              v-else
              v-auth="{ authArr: auth, key: 'edit' }"
              type="primary"
              :icon="Edit"
              link
              @click="() => baseRef?.onEdit().then(() => (collapseEdit[CollapseItem.base] = true))"
            >
              {{ $t("merak.edit") }}
            </el-button>
          </template>
          <Base ref="baseRef" :isEdit="collapseEdit[CollapseItem.base]" :queueId="queueId" />
        </MerakCollapseItem>
        <MerakCollapseItem :name="CollapseItem.factory">
          <template #title>
            <span>{{ collapseTitle[CollapseItem.factory] }}</span>
            <span class="remark">&nbsp;&nbsp;&#40;{{ $t("goods_allocation_merge.have") }}</span>
            <span class="remark orange">&nbsp;{{ factoryRef?.recordNum ?? 0 }}&nbsp;</span>
            <span class="remark">{{ $t("goods_allocation_merge.records") }}&#41;</span>
          </template>
          <template #handler>
            <template v-if="collapseEdit[CollapseItem.factory]">
              <el-button @click="() => factoryRef?.onCancel().then(() => (collapseEdit[CollapseItem.factory] = false))">
                {{ $t("merak.cancel") }}
              </el-button>
              <el-button type="primary" plain @click="factoryRef?.onAddFactory">{{ $t("goods_document.add_factory") }}</el-button>
              <el-button
                type="primary"
                @click="() => factoryRef?.onSave().then(() => (collapseEdit[CollapseItem.factory] = false))"
              >
                {{ $t("merak.save") }}
              </el-button>
            </template>
            <el-button
              v-else
              v-auth="{ authArr: auth, key: 'edit' }"
              type="primary"
              :icon="Edit"
              link
              @click="() => factoryRef?.onEidt().then(() => (collapseEdit[CollapseItem.factory] = true))"
            >
              {{ $t("merak.edit") }}
            </el-button>
          </template>
          <Factory ref="factoryRef" :isEdit="collapseEdit[CollapseItem.factory]" :queueId="queueId" />
        </MerakCollapseItem>
        <MerakCollapseItem :name="CollapseItem.brand">
          <template #title>
            <span>{{ collapseTitle[CollapseItem.brand] }}</span>
            <span class="remark">&nbsp;&nbsp;&#40;{{ $t("goods_allocation_merge.have") }}</span>
            <span class="remark orange">&nbsp;{{ brandRef?.recordNum ?? 0 }}&nbsp;</span>
            <span class="remark">{{ $t("goods_allocation_merge.records") }}&#41;</span>
          </template>
          <Brand ref="brandRef" :queueId="queueId" />
        </MerakCollapseItem>
        <MerakCollapseItem :name="CollapseItem.enterprise">
          <template #title>
            <span>{{ collapseTitle[CollapseItem.enterprise] }}</span>
            <span class="remark">&nbsp;&nbsp;&#40;{{ $t("goods_allocation_merge.have") }}</span>
            <span class="remark orange">&nbsp;{{ enterpriseRef?.recordNum ?? 0 }}&nbsp;</span>
            <span class="remark">{{ $t("goods_allocation_merge.records") }}&#41;</span>
          </template>
          <Enterprise ref="enterpriseRef" :queueId="queueId" />
        </MerakCollapseItem>
        <MerakCollapseItem :name="CollapseItem.annex">
          <template #title>
            <span>{{ collapseTitle[CollapseItem.annex] }}</span>
            <span class="remark">&nbsp;&nbsp;&#40;{{ $t("goods_allocation_merge.have") }}</span>
            <span class="remark orange">&nbsp;{{ annexRef?.recordNum ?? 0 }}&nbsp;</span>
            <span class="remark">{{ $t("goods_allocation_merge.records") }}&#41;</span>
          </template>
          <template #handler>
            <template v-if="collapseEdit[CollapseItem.annex]">
              <el-button @click="() => annexRef?.onCancel().then(() => (collapseEdit[CollapseItem.annex] = false))">
                {{ $t("merak.cancel") }}
              </el-button>
              <el-button type="primary" @click="() => annexRef?.onSave().then(() => (collapseEdit[CollapseItem.annex] = false))">
                {{ $t("merak.save") }}
              </el-button>
            </template>
            <el-button
              v-else
              v-auth="{ authArr: auth, key: 'edit' }"
              type="primary"
              :icon="Edit"
              link
              @click="() => annexRef?.onEdit().then(() => (collapseEdit[CollapseItem.annex] = true))"
            >
              {{ $t("merak.edit") }}
            </el-button>
          </template>
          <Annex
            ref="annexRef"
            :isEdit="collapseEdit[CollapseItem.annex]"
            :queueId="queueId"
            @change="scrollRef?.setScrollTop(queueLoading || !ignoreScroll ? 0 : 99999)"
          />
        </MerakCollapseItem>
      </MerakCollapse>
    </el-scrollbar>
  </div>
</template>

<script setup lang="ts" name="goodsDocumentCard">
import { getCurrentInstance, ref, reactive, onMounted, onActivated, onDeactivated } from "vue";

import useLoading from "@/hooks/useLoading";

import { ElScrollbar, ElButton } from "element-plus";

import { Edit } from "@element-plus/icons-vue";

import { MerakCollapse, MerakCollapseItem } from "@/components/MerakCollapse";

import Base from "./components/Base.vue";
import Brand from "./components/Brand.vue";
import Factory from "./components/Factory.vue";
import Enterprise from "./components/Enterprise.vue";
import Annex from "./components/Annex.vue";

import { ResultEnum } from "@/enums/httpEnum";
import { UserAuthType, getUserAuth } from "@/api/modules/user";

const enum CollapseItem {
  base = "base",
  brand = "brand",
  factory = "factory",
  enterprise = "enterprise",
  annex = "annex"
}

const currentInstance = getCurrentInstance();

const { queueId, queueLoading } = useLoading();

const containerRef = ref<HTMLDivElement>();

const baseRef = ref<InstanceType<typeof Base>>();
const brandRef = ref<InstanceType<typeof Brand>>();
const factoryRef = ref<InstanceType<typeof Factory>>();
const enterpriseRef = ref<InstanceType<typeof Enterprise>>();
const annexRef = ref<InstanceType<typeof Annex>>();

const scrollRef = ref<InstanceType<typeof ElScrollbar>>();

const auth = ref<UserAuthType>({});

const ignoreScroll = ref(false);

const collapseActive = reactive([
  CollapseItem.base,
  CollapseItem.brand,
  CollapseItem.factory,
  CollapseItem.enterprise,
  CollapseItem.annex
]);

const collapseTitle = reactive({
  [CollapseItem.base]: currentInstance?.proxy?.$t("goods_document.base_info"),
  [CollapseItem.brand]: currentInstance?.proxy?.$t("goods_document.system_brand"),
  [CollapseItem.factory]: currentInstance?.proxy?.$t("goods_document.factory"),
  [CollapseItem.enterprise]: currentInstance?.proxy?.$t("goods_document.enterprise"),
  [CollapseItem.annex]: currentInstance?.proxy?.$t("goods_document.annex")
});

const collapseEdit = reactive({
  [CollapseItem.base]: false,
  [CollapseItem.factory]: false,
  [CollapseItem.annex]: false
});

// 类锚点滚动
const scrollToKey = (key: CollapseItem) => {
  const node = containerRef.value?.querySelector(`[data-name=${key}]`);
  if (!node) return;
  node.scrollIntoView({ behavior: "smooth" });
};

// 保存表单
const handleSaveBase = () => {
  baseRef.value?.onSave()?.then(() => {
    brandRef.value?.reload();
    enterpriseRef.value?.reload();
    collapseEdit[CollapseItem.base] = false;
  });
};

onMounted(() => {
  getUserAuth("goods_document", queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      auth.value = data;
    }
  });
});

onActivated(() => {
  // 调用时机为首次挂载
  // 以及每次从缓存中被重新插入时
  const ignoreTimer = setTimeout(() => {
    ignoreScroll.value = true;
    clearTimeout(ignoreTimer);
  }, 1000);
});

onDeactivated(() => {
  // 在从 DOM 上移除、进入缓存
  // 以及组件卸载时调用
  ignoreScroll.value = false;
});
</script>

<style scoped lang="scss">
.container {
  height: 100%;
  color: var(--merak-text-color);
  font-size: var(--merak-text-size);
  .title {
    position: sticky;
    top: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: var(--merak-space);
    padding: var(--merak-padding);
    background-color: var(--el-bg-color);
    z-index: 1;
    &-link .el-button.is-link {
      position: relative;
      margin-left: var(--merak-padding);
      padding: 0;
      min-width: auto;
      &:not(:first-child)::before {
        content: "";
        position: absolute;
        top: 50%;
        left: calc(0px - var(--merak-space));
        width: 1px;
        height: 80%;
        background-color: var(--merak-text-color);
        transform: translateY(-50%);
      }
      &:hover {
        color: var(--el-color-primary) !important;
      }
    }
  }
  .el-scrollbar {
    height: calc(100% - 68px);
    .el-button.is-link {
      padding: 0;
      min-width: auto;
    }
  }
}
.remark {
  color: #cfd3dc;
  font-size: 12px;
  &.orange {
    color: orange;
  }
}
</style>
